// Modules to control application life and create native browser window
const {app, BrowserWindow, autoUpdater, ipcMain: ipc, dialog} = require('electron')
if (require('electron-squirrel-startup')) return;
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

const feedUrl = `D:\\github\\electron\\electron-packager-test\\tmp\\build\\installer64`; // 更新包位置

startupEventHandle();

function createWindow() {
    // Create the browser window.

    mainWindow = new BrowserWindow({width: 800, height: 600})
    mainWindow.once('ready-to-show', () => {
        console.log('渲染之前');
    })
    // and load the index.html of the app.
    mainWindow.loadFile('index.html')

    ipc.on('update', function (event, arg) {
        dialog.showMessageBox(mainWindow, {message: "message!"});
        startupEventHandle();
    });

    ipc.on('check-for-update', function (event, arg) {
        let appName = '400电话系统';
        let appIcon = __dirname + '/icon.ico';
        let message = {
            error: '检查更新出错',
            checking: '正在检查更新……',
            updateAva: '下载更新成功',
            updateNotAva: '现在使用的就是最新版本，不用更新',
            downloaded: '最新版本已下载，将在重启程序后更新'
        };
        const os = require('os');
        autoUpdater.setFeedURL(feedUrl);
        autoUpdater.on('error', function (error) {
            return dialog.showMessageBox(mainWindow, {
                type: 'info',
                icon: appIcon,
                buttons: ['OK'],
                title: appName,
                message: message.error,
                detail: '\r' + error
            });
        })
            .on('checking-for-update', function (e) {
                return dialog.showMessageBox(mainWindow, {
                    type: 'info',
                    icon: appIcon,
                    buttons: ['OK'],
                    title: appName,
                    message: message.checking
                });
            })
            .on('update-available', function (e) {
                var downloadConfirmation = dialog.showMessageBox(mainWindow, {
                    type: 'info',
                    icon: appIcon,
                    buttons: ['OK'],
                    title: appName,
                    message: message.updateAva
                });
                if (downloadConfirmation === 0) {
                    return;
                }
            })
            .on('update-not-available', function (e) {
                return dialog.showMessageBox(mainWindow, {
                    type: 'info',
                    icon: appIcon,
                    buttons: ['OK'],
                    title: appName,
                    message: message.updateNotAva
                });
            })
            .on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
                var index = dialog.showMessageBox(mainWindow, {
                    type: 'info',
                    icon: appIcon,
                    buttons: ['现在重启', '稍后重启'],
                    title: appName,
                    message: message.downloaded,
                    detail: releaseName + "\n\n" + releaseNotes
                });
                if (index === 1) return;
                autoUpdater.quitAndInstall();
            });
        autoUpdater.checkForUpdates();
    });

    // Open the DevTools.
    // mainWindow.webContents.openDevTools()

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.
        mainWindow = null
    })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', function () {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        updateHandle()
    }
})


function startupEventHandle() {
    if (require('electron-squirrel-startup')) return;
    var handleStartupEvent = function () {
        if (process.platform !== 'win32') {
            return false;
        }
        var squirrelCommand = process.argv[1];
        switch (squirrelCommand) {
            case '--squirrel-install':
            case '--squirrel-updated':
                install();
                return true;
            case '--squirrel-uninstall':
                uninstall();
                app.quit();
                return true;
            case '--squirrel-obsolete':
                app.quit();
                return true;
        }

        // 安装
        function install() {
            var cp = require('child_process');
            var updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
            var target = path.basename(process.execPath);
            var child = cp.spawn(updateDotExe, ["--createShortcut", target], {detached: true});
            child.on('close', function (code) {
                app.quit();
            });
        }

        // 卸载
        function uninstall() {
            var cp = require('child_process');
            var updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
            var target = path.basename(process.execPath);
            var child = cp.spawn(updateDotExe, ["--removeShortcut", target], {detached: true});
            child.on('close', function (code) {
                app.quit();
            });
        }
    };
    if (handleStartupEvent()) {
        return;
    }
}

function updateHandle() {

}

// 主进程主动发送消息给渲染进程函数
function sendUpdateMessage(message, data) {
    console.log({message, data});
    dialog.showMessageBox(mainWindow, {
        message: JSON.stringify({
            message,
            data
        })
    });
    //webContents.send('message', { message, data });
}

 /**
  * 如果想使用electron-updater更新可按下方进行配置
  * 更新地址需要配置
  * https://www.electron.build/auto-update
  *"publish": [{
    "provider": "generic", //generic 方式是针对可以直接上传不需要验证的服务器，无需格外配置信息。
    "url": "http://127.0.0.1:8080/0.0.5/"
  }]
  */

// import {
//   autoUpdater
// } from 'electron-updater'
// import logger from 'electron-log'


// autoUpdater.channel = 'latest'
// autoUpdater.allowDowngrade = false

// autoUpdater.logger = logger
// autoUpdater.logger.transports.file.level = 'silly'
// autoUpdater.logger.transports.file.appName = 'private repo'
// autoUpdater.autoDownload = true

// autoUpdater.on('update-downloaded', () => {
//   dialog.showMessageBox({
//     message: 'update Downloaded !!'
//   })
// })

// autoUpdater.on('checking-for-update', () => {
//   dialog.showMessageBox({
//     message: 'CHECKING FOR UPDATES !!'
//   })
// })

// autoUpdater.on('update-available', () => {
//   dialog.showMessageBox({
//     message: ' update-available !!'
//   })
// })

// autoUpdater.on('error', (error) => {
//   autoUpdater.logger.debug(error)
// })

// app.on('ready', () => {
//   if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
// })
